package com.sxfans.util;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketServerUtils {
	public static void main(String[] args) {
		SocketServerUtils serverUtils = new SocketServerUtils();
		serverUtils.Open(8888, 0,false);
		System.out.println("************************");
		System.out.println("************************");
	}
	private ServerSocket serverSocket;
    private static ExecutorService executorService;//线程池
    private final static int POOL_SIZE = 10;
	
	static {
		executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
	}

	public void Open(int port, int so_timeout , boolean isLong) {
		try
		{
			serverSocket = new ServerSocket(port);
			if (so_timeout != 0)
			{
				serverSocket.setSoTimeout(so_timeout);
			}
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		while (true){
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				executorService.execute(new Handler(socket,isLong));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	class Handler implements Runnable{
		private Socket socket;
		private boolean isLong;
		public Handler(Socket socket,boolean isLong){
	        this.socket = socket;
	        this.isLong = isLong;
	    }
		
		@Override
		public void run() {
			BufferedReader br = null;
			BufferedWriter pw = null;
			try
			{
				br = getReader(socket);
				pw = getWriter(socket);
				String readLine = "";
				if(isLong)
				{
					while((readLine=br.readLine()) != null)
					{
						System.out.println(readLine);
					}
				}
				else
				{
					readLine = br.readLine();
					System.out.println(readLine);
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
			finally{
				try {
					pw.flush();
					pw.close();
					br.close();
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		private BufferedWriter getWriter(Socket socket) throws IOException{
	        OutputStream socketOut=socket.getOutputStream();
	        return new BufferedWriter(new OutputStreamWriter(socketOut));
	    }
		
	    private BufferedReader getReader(Socket socket) throws IOException{
	        InputStream socketIn=socket.getInputStream();
	        return new BufferedReader(new InputStreamReader(socketIn));
	    }
	}
}
